import sys, os, django
 
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #把manage.py所在目录添加到系统目录
os.environ['DJANGO_SETTINGS_MODULE'] = 'hg_survey.settings' #设置setting文件
django.setup()#初始化Django环境

import pandas as pd
from students.models import  Student
from survey.serializer import SurveyDetailSerializer
from survey.models import Survey, Question, AnswerSet
from hg_survey.logging import evt_logger

import random
import json

def create_test_answer(survey_id):
    students = Student.objects.all()
    survey = Survey.objects.get(pk=survey_id)
    question_set = Question.objects.filter(survey_id=survey.survey_id)
    serializer = SurveyDetailSerializer(survey, context={'question_set': question_set})
    data = serializer.data
    for student in students:
        ans = {}
        for question in data['question_list']:
            op_length = len(question.get('options',[]))
            if question.get('qtype') == 'radio':
                rdx = random.randint(0, op_length - 1)
                ans.update({question['qid']: [question['options'][rdx]['id']]})
            elif question.get('qtype') == 'checkbox':
                rdx = random.randint(0, op_length - 1)
                choices = random.sample(range(op_length), rdx)
                ans.update({
                    question['qid']: [question['options'][i]['id'] for i in choices]
                })
            else:
                ans.update({ 
                    question['qid']: [random.randint(0, 10000)]
                })
        ans_set = AnswerSet(survey=survey,
                            student=student,
                            answer=json.dumps(ans))
        ans_set.save()
        evt_logger.info(f'{student} save answer')

if __name__ == '__main__':
    survey_id = "test-2018-survey-01"
    create_test_answer(survey_id)